var Mongoose = require('mongoose'),
    comments = require('./comment'),
    abuses = require('./abuse'),
    votes = require('./vote'),
    users = require('../models/user'),
    util = require('../helpers/util');

var ideaSchema = Mongoose.Schema({
    user: {
        type: Mongoose.Schema.ObjectId,
        required: true,
        ref: 'User'
    },
    comment: {
        type: Mongoose.Schema.ObjectId,
        ref: 'Comment'
    },
    tags: {
        type: [String],
        limit: 10
    },
    title: {
        type: String,
        required: true,
        trim: true
    },
    content: {
        type: String
    },
    citation: {},
    citationArray: {
        type: [String]
    },
    favorite: [{
        type: Mongoose.Schema.ObjectId,
        ref: 'User'
    }],
    likes: {
        type: Number,
        default: 0
    },
    dislikes: {
        type: Number,
        default: 0
    },
    commentCount: {
        type: Number,
        default: 0
    },
    points: {
        type: Number,
        default: 0
    },
    spam: {
        type: Boolean,
        default: false
    },
    abuse: [{
        user: {type: Mongoose.Schema.ObjectId, ref: 'User'},
        reason: {type: String, default: ''}
    }],
    keyword: [{
        Id: {type: Mongoose.Schema.ObjectId, ref: 'Keyword'},
        content: {type: String, default: ''},
        count: {type: Number, default: 1}
    }],
    complex: {
        type: String
    }
}, {timestamps: true});

var Idea = Mongoose.model('Idea', ideaSchema);

Idea.createIdea = function (newIdea, callback) {
    newIdea.save(callback);
};

Idea.getTitle = function (key, callback) {
    Idea.find({title: {$regex: key, $options: '$i'}}, {title: 1, _id: 0}, {limit: 40}, callback);
};

Idea.getTags = function (key, callback) {
    Idea.aggregate([
        {
            $unwind: "$tags"
        },
        {$group: {_id: "$tags"}},
        {
            $group: {
                _id: 0,
                tags: {$push: '$_id'},
                count: {$sum: 1}
            }
        }
    ], callback);
};

Idea.getIdea = function (userId, user, params, callback) {
    var skipItem = params.skipItem || 0,
        itemsperPage = params.itemsperPage || 6,
        sortParameter = params.sortParameter || 'createdAt',
        sortOrder = ((params.sortOrder === 'ascending') ? 1 : -1),
        sort = {},
        skip = parseInt(skipItem),
        limit = parseInt(itemsperPage),
        title = params.sortByTitle || '',
        tags = params.sortByTags || '',
        author = params.sortByAuthor || '',
        inputFromDate = params.fromDate,
        toDate = params.toDate;
    sort[sortParameter] = sortOrder;
    if (sortParameter != 'createdAt') {
        sort['createdAt'] = -1;
    }
    var fromDate = util.getDateWithoutTimeStamp(inputFromDate);
    var todate1 = util.getDateWithoutTimeStamp(toDate);
    var endDate = new Date(todate1.getTime() + (24 * 60 * 60 * 1000));
    var searchMatch = {};
    var tagsReg = [];
    if (tags) {
        tags.forEach(function (val) {
            tagsReg.push(new RegExp(val, "i"));
        });
    }
    if (title && title.length > 0) {
        searchMatch = {$and: [{title: {$regex: title, $options: '$i'}}, {createdAt: {$gte: fromDate, $lt: endDate}}]};
    }
    else if (tags && tags.length > 0) {
        searchMatch = {$and: [{tags: {$in: tagsReg}}, {createdAt: {$gte: fromDate, $lt: endDate}}]};
    }
    else {
        var searchSpam = {$or: [{"spam": {$exists: false}}, {"spam": false}]};
        searchMatch = {$and: [{createdAt: {$gte: fromDate, $lt: endDate}}, searchSpam]};
    }




    Idea.aggregate([
        {$match: searchMatch},
        {
            "$project": {
                "_id": "$_id",
                "otitle": "$title",
                "title": {"$toLower": "$title"},
                "user": "$user",
                "content": "$content",
                "createdAt": "$createdAt",
                "dislikes": "$dislikes",
                "likes": "$likes",
                "likesCount": {$sum: ["$likes", "$dislikes"]},
                "tags": "$tags",
                "favorite": "$favorite",
                "commentCount": "$commentCount",
                "abuseCount": "$abuseCount",
                "points": "$points",
                "keyword": "$keyword",
                "citation": "$citation",
                "citationArray": "$citationArray",
                "spam": "$spam"
            }
        },
        {
            $lookup: {
                "from": "users",
                "localField": "user",
                "foreignField": "_id",
                "as": "users"
            }
        },
        {
            $unwind: "$users"
        },
        {
            "$project": {
                "_id": "$_id",
                "title": "$title",
                "otitle": "$otitle",
                "name": {$concat: ["$users.firstName", " ", {$ifNull: ["$users.lastName", " "]}]},
                "content": "$content",
                "createdAt": "$createdAt",
                "user": "$user",
                "dislikes": "$dislikes",
                "likes": "$likes",
                "likesCount": {$sum: ["$likes", "$dislikes"]},
                "tags": "$tags",
                "favorite": "$favorite",
                "favouriteCount": {$size: "$favorite"},
                "commentCount": "$commentCount",
                "abuseCount": "$abuseCount",
                "points": "$points",
                "keyword": "$keyword",
                "citation": "$citation",
                "citationArray": "$citationArray",
                "spam": "$spam"
            }
        },
        {$match: {"name": {$regex: author, $options: '$i'}}},


        {"$sort": sort},
        {"$skip": skip},
        {"$limit": limit},
        {
            $lookup: {
                "from": "votes",
                "localField": "_id",
                "foreignField": "idea",
                "as": "vote"
            }
        },
        {
            "$project": {
                "_id": "$_id",
                "title": "$otitle",
                "name": "$name",
                "content": "$content",
                "createdAt": "$createdAt",
                "user": "$user",
                "dislikes": "$dislikes",
                "likes": "$likes",
                "likesCount": {$sum: ["$likes", "$dislikes"]},
                "tags": "$tags",
                "isfavorite": {
                    $filter: {
                        input: "$favorite",
                        as: "num",
                        cond: {$eq: ['$$num', Mongoose.Types.ObjectId(user._id)]}
                    }
                },
                "isliked": {
                    $filter: {
                        input: "$vote",
                        as: "num",
                        cond: {$and: [{$eq: ['$$num.voteType', "like"]}, {$eq: ['$$num.user', Mongoose.Types.ObjectId(user._id)]}]}
                    }
                },
                "isdisliked": {
                    $filter: {
                        input: "$vote",
                        as: "num",
                        cond: {$and: [{$eq: ['$$num.voteType', "dislike"]}, {$eq: ['$$num.user', Mongoose.Types.ObjectId(user._id)]}]}
                    }
                },
                "commentCount": "$commentCount",
                "abuseCount": "$abuseCount",
                "points": "$points",
                "keyword": "$keyword",
                "citation": "$citation",
                "citationArray": "$citationArray",
                "spam": "$spam"
            }
        },
        {
            "$project": {
                "_id": "$_id",
                "title": "$title",
                "name": "$name",
                "content": "$content",
                "createdAt": "$createdAt",
                "user": "$user",
                "dislikes": "$dislikes",
                "likes": "$likes",
                "likesCount": {$sum: ["$likes", "$dislikes"]},
                "tags": "$tags",
                "isfavorite": {"$cond": [{"$gte": [{$size: "$isfavorite"}, 1]}, true, false]},
                "isliked": {"$cond": [{"$gte": [{$size: "$isliked"}, 1]}, true, false]},
                "isdisliked": {"$cond": [{"$gte": [{$size: "$isdisliked"}, 1]}, true, false]},
                "commentCount": "$commentCount",
                "abuseCount": "$abuseCount",
                "isOwner": {$eq: ["$user", Mongoose.Types.ObjectId(userId)]},
                "points": "$points",
                "keyword": "$keyword",
                "citation": "$citation",
                "citationArray": "$citationArray",
                "spam": "$spam"
            }
        },
        {
            $lookup: {
                "from": "abuses",
                "localField": "_id",
                "foreignField": "idea",
                "as": "abuse"
            }
        },
        {
            "$project": {
                "_id": "$_id",
                "title": "$title",
                "name": "$name",
                "content": "$content",
                "createdAt": "$createdAt",
                "user": "$user",
                "dislikes": "$dislikes",
                "likes": "$likes",
                "likesCount": "$likesCount",
                "tags": "$tags",
                "isfavorite": "$isfavorite",
                "isliked": "$isliked",
                "isdisliked": "$isdisliked",
                "commentCount": "$commentCount",
                "abuseCount": "$abuseCount",
                "isOwner": "$isOwner",
                "isAbused": {
                    $filter: {
                        input: "$abuse",
                        as: "num",
                        cond: {$and: [{$eq: ['$$num.user', Mongoose.Types.ObjectId(user._id)]}]}
                    }
                },
                "points": "$points",
                "keyword": "$keyword",
                "citation": "$citation",
                "citationArray": "$citationArray",
                "spam": "$spam"
            }
        },
        {
            "$project": {
                "_id": "$_id",
                "title": "$title",
                "name": "$name",
                "content": "$content",
                "createdAt": "$createdAt",
                "user": "$user",
                "dislikes": "$dislikes",
                "likes": "$likes",
                "likesCount": "$likesCount",
                "tags": "$tags",
                "isfavorite": "$isfavorite",
                "isliked": "$isliked",
                "isdisliked": "$isdisliked",
                "commentcount": "$commentCount",
                "abuseCount": "$abuseCount",
                "isOwner": "$isOwner",
                "isAbused": {"$cond": [{"$gte": [{$size: "$isAbused"}, 1]}, true, false]},
                "points": "$points",
                "keyword": "$keyword",
                "citation": "$citation",
                "citationArray": "$citationArray",
                "spam": "$spam"
            }
        }

    ], callback);
};

Idea.getOneIdea = function (IDEA, userId, callback) {
    Idea.aggregate([
        {$match: {title: IDEA.title}},
        {
            "$project": {
                "_id": "$_id",
                "otitle": "$title",
                "title": {"$toLower": "$title"},
                "user": "$user",
                "content": "$content",
                "createdAt": "$createdAt",
                "dislikes": "$dislikes",
                "likes": "$likes",
                "likesCount": {$sum: ["$likes", "$dislikes"]},
                "tags": "$tags",
                "favorite": "$favorite",
                "commentCount": "$commentCount",
                "citation": "$citation",
                "citationArray": "$citationArray",
                "abuseCount": "$abuseCount"
            }
        },

        {
            $lookup: {
                "from": "users",
                "localField": "user",
                "foreignField": "_id",
                "as": "users"
            }
        },
        {
            $unwind: "$users"
        },
        {
            "$project": {
                "_id": "$_id",
                "title": "$title",
                "otitle": "$otitle",
                "name": {$concat: ["$users.firstName", " ", {$ifNull: ["$users.lastName", " "]}]},
                "content": "$content",
                "createdAt": "$createdAt",
                "user": "$user",
                "dislikes": "$dislikes",
                "likes": "$likes",
                "likesCount": {$sum: ["$likes", "$dislikes"]},
                "tags": "$tags",
                "favorite": "$favorite",
                "favouriteCount": {$size: "$favorite"},
                "commentCount": "$commentCount",
                "citation": "$citation",
                "citationArray": "$citationArray",
                "abuseCount": "$abuseCount"
            }
        },
        {
            $lookup: {
                "from": "votes",
                "localField": "_id",
                "foreignField": "idea",
                "as": "vote"
            }
        },
        {
            "$project": {
                "_id": "$_id",
                "title": "$otitle",
                "name": "$name",
                "content": "$content",
                "createdAt": "$createdAt",
                "user": "$user",
                "dislikes": "$dislikes",
                "likes": "$likes",
                "likesCount": {$sum: ["$likes", "$dislikes"]},
                "tags": "$tags",
                "isfavorite": {
                    $filter: {
                        input: "$favorite",
                        as: "num",
                        cond: {$eq: ['$$num', Mongoose.Types.ObjectId(userId)]}
                    }
                },
                "isliked": {
                    $filter: {
                        input: "$vote",
                        as: "num",
                        cond: {$and: [{$eq: ['$$num.voteType', "like"]}, {$eq: ['$$num.user', Mongoose.Types.ObjectId(userId)]}]}
                    }
                },
                "isdisliked": {
                    $filter: {
                        input: "$vote",
                        as: "num",
                        cond: {$and: [{$eq: ['$$num.voteType', "dislike"]}, {$eq: ['$$num.user', Mongoose.Types.ObjectId(userId)]}]}
                    }
                },
                "commentCount": "$commentCount",
                "citation": "$citation",
                "citationArray": "$citationArray",
                "abuseCount": "$abuseCount"
            }
        },
        {
            "$project": {
                "_id": "$_id",
                "title": "$title",
                "name": "$name",
                "content": "$content",
                "createdAt": "$createdAt",
                "user": "$user",
                "dislikes": "$dislikes",
                "likes": "$likes",
                "likesCount": {$sum: ["$likes", "$dislikes"]},
                "tags": "$tags",
                "isfavorite": {"$cond": [{"$gte": [{$size: "$isfavorite"}, 1]}, true, false]},
                "isliked": {"$cond": [{"$gte": [{$size: "$isliked"}, 1]}, true, false]},
                "isdisliked": {"$cond": [{"$gte": [{$size: "$isdisliked"}, 1]}, true, false]},
                "commentCount": "$commentCount",
                "abuseCount": "$abuseCount",
                "citation": "$citation",
                "citationArray": "$citationArray",
                "isOwner": {$eq: ["$user", Mongoose.Types.ObjectId(userId)]}
            }
        },
        {
            $lookup: {
                "from": "abuses",
                "localField": "_id",
                "foreignField": "idea",
                "as": "abuse"
            }
        },
        {
            "$project": {
                "_id": "$_id",
                "title": "$title",
                "name": "$name",
                "content": "$content",
                "createdAt": "$createdAt",
                "user": "$user",
                "dislikes": "$dislikes",
                "likes": "$likes",
                "likesCount": "$likesCount",
                "tags": "$tags",
                "isfavorite": "$isfavorite",
                "isliked": "$isliked",
                "isdisliked": "$isdisliked",
                "commentCount": "$commentCount",
                "abuseCount": "$abuseCount",
                "isOwner": "$isOwner",
                "citation": "$citation",
                "citationArray": "$citationArray",
                "isAbused": {
                    $filter: {
                        input: "$abuse",
                        as: "num",
                        cond: {$and: [{$eq: ['$$num.user', Mongoose.Types.ObjectId(userId)]}]}
                    }
                },
            }
        },
        {
            "$project": {
                "_id": "$_id",
                "title": "$title",
                "name": "$name",
                "content": "$content",
                "createdAt": "$createdAt",
                "user": "$user",
                "dislikes": "$dislikes",
                "likes": "$likes",
                "likesCount": "$likesCount",
                "tags": "$tags",
                "isfavorite": "$isfavorite",
                "isliked": "$isliked",
                "isdisliked": "$isdisliked",
                "commentcount": "$commentCount",
                "abuseCount": "$abuseCount",
                "isOwner": "$isOwner",
                "citation": "$citation",
                "citationArray": "$citationArray",
                "isAbused": {"$cond": [{"$gte": [{$size: "$isAbused"}, 1]}, true, false]}
            }
        }
    ], callback);
};

Idea.getFilteredIdeaCount = function (params, callback) {
    var sortParameter = params.sortParameter || 'createdAt',
        sortOrder = ((params.sortOrder === 'ascending') ? 1 : -1),
        sort = {},
        title = params.sortByTitle || '',
        tags = params.sortByTags || '',
        author = params.sortByAuthor || '',
        inputfromDate = params.fromDate,
        toDate = params.toDate;
    sort[sortParameter] = sortOrder;
    var fromDate = util.getDateWithoutTimeStamp(inputfromDate);
    var todate1 = util.getDateWithoutTimeStamp(toDate);
    var endDate = new Date(todate1.getTime() + (24 * 60 * 60 * 1000));
    var searchMatch = {};
    var tagsReg = [];
    if (tags) {
        tags.forEach(function (val) {
            tagsReg.push(new RegExp(val, "i"));
        });
    }
    if (title && title.length > 0) {
        searchMatch = {$and: [{title: {$regex: title, $options: '$i'}}, {createdAt: {$gte: fromDate, $lt: endDate}}]};
    }
    else if (tags && tags.length > 0) {
        searchMatch = {$and: [{tags: {$in: tagsReg}}, {createdAt: {$gte: fromDate, $lt: endDate}}]};
    }
    else {
        searchMatch = {createdAt: {$gte: fromDate, $lt: endDate}};
    }
    Idea.aggregate([
        {$match: searchMatch},
        {
            "$project": {
                "otitle": "$title",
                "title": {"$toLower": "$title"},
                "user": "$user",
                "content": "$content",
                "createdAt": "$createdAt",
                "dislikes": "$dislikes",
                "likes": "$likes",
                "tags": "$tags",
                "favorite": "$favorite"
            }
        },

        {
            $lookup: {
                "from": "users",
                "localField": "user",
                "foreignField": "_id",
                "as": "users"
            }
        },
        {
            $unwind: "$users"
        },
        {
            "$project": {
                "title": "$otitle",
                "name": {$concat: ["$users.firstName", " ", {$ifNull: ["$users.lastName", " "]}]},
                "content": "$content",
                "createdAt": "$createdAt",
                "dislikes": "$dislikes",
                "likes": "$likes",
                "tags": "$tags",
                "favorite": "$favorite"
            }
        },
        {$match: {"name": {$regex: author, $options: '$i'}}},
        {$group: {_id: null, count: {$sum: 1}}}

    ], callback);
};

Idea.getIdeaById = function (id, callback) {
    Idea.findById(id, callback);
};

Idea.getIdeaCount = function (callback) {
    Idea.count(callback);
};

Idea.addFavoriteIdea = function (user, idea, callback) {
    Idea.find({_id: new Mongoose.Types.ObjectId(idea), favorite: user._id}, function (err, ideaList) {
        if (err) throw err;
        else if (ideaList.length == 0) {
            Idea.update({_id: new Mongoose.Types.ObjectId(idea)}, {$push: {favorite: user._id}}, callback);
        }
        else {
            callback();
        }
    });
};

Idea.removeFavoriteIdea = function (user, idea, callback) {
    Idea.update({_id: new Mongoose.Types.ObjectId(idea)}, {$pull: {favorite: user._id}}, callback);
};

Idea.updateCommentCount = function (id) {
    Idea.findById(id, function (err, idea) {
        if (err) {
            throw err;
        }
        else {
            comments.getIdeaCommentCount(id, function (err, count) {
                if (!err) {
                    idea.commentCount = count;
                    idea.save();
                }
            })
        }
    });
};

Idea.updateAbuseCount = function (id) {
    Idea.findById(id, function (err, idea) {
        if (err) {
            throw err;
        }
        else {
            abuses.getIdeaAbuseCount(id, function (err, count) {
                if (!err) {
                    idea.abuseCount = count;
                    idea.save();
                }
            })
        }
    });
};

Idea.updateVoteCount = function (id, voteType) {
    Idea.findById(id, function (err, idea) {
        if (err) {
            throw err;
        }
        else {
            votes.getIdeaVoteCount(id, "like", function (err, count) {
                idea.likes = count;
                idea.save();
            });
            votes.getIdeaVoteCount(id, "dislike", function (err, count) {
                idea.dislikes = count;
                idea.save();
            });
        }
    });
};

Idea.updatePoints = function (ideaId, voteType, isUser) {
    Idea.findById(ideaId, function (err, idea) {
        if (!err) {
            var points = idea.points;
            if (isUser == "0") {
                if (voteType == "like") {
                    idea.points = points + 1;
                    idea.save();
                } else {
                    idea.points = points - 1;
                    idea.save();
                }
            } else if (isUser == "1") {
                if (voteType == "like") {
                    idea.points = points + 2;
                    idea.save();
                } else {
                    idea.points = points - 2;
                    idea.save();
                }
            } else if (isUser == "2") {
                if (voteType == "like") {
                    idea.points = points - 1;
                    idea.save();
                } else {
                    idea.points = points + 1;
                    idea.save();
                }
            }
        }
    });
};

Idea.updateVoteData = function (ideaId, voteType, isUser, callback) {
    Idea.findById(ideaId, function (err, idea) {
        if (err) {
            throw err;
        }
        else {
            votes.getIdeaVoteCount(ideaId, "like", function (err, count) {
                idea.likes = count;
                idea.save();
            });
            votes.getIdeaVoteCount(ideaId, "dislike", function (err, count) {
                idea.dislikes = count;
                idea.save();
            });
        }
    });
    Idea.findById(ideaId, function (err, idea) {
        if (!err) {
            var points = idea.points;
            if (isUser == "0") {
                if (voteType == "like") {
                    idea.points = points + 1;
                    idea.save(callback);
                } else {
                    idea.points = points - 1;
                    idea.save(callback);
                }
            } else if (isUser == "1") {
                if (voteType == "like") {
                    idea.points = points + 2;
                    idea.save(callback);
                } else {
                    idea.points = points - 2;
                    idea.save(callback);
                }
            } else if (isUser == "2") {
                if (voteType == "like") {
                    idea.points = points - 1;
                    idea.save(callback);
                } else {
                    idea.points = points + 1;
                    idea.save(callback);
                }
            }
        }
    });
}


Idea.recentIdeasByUser = function (userId, params, callback) {
    var inputFromDate = params.fromDate,
        toDate = params.toDate,
        fromDate = util.getDateWithoutTimeStamp(inputFromDate),
        todate1 = util.getDateWithoutTimeStamp(toDate),
        endDate = new Date(todate1.getTime() + (24 * 60 * 60 * 1000));
    Idea.find({createdAt: {$gte: fromDate, $lt: endDate}, user: Mongoose.Types.ObjectId(userId)}, callback);
};

Idea.getIdeasByUserId = function (userId, callback) {
    Idea.find({user: Mongoose.Types.ObjectId(userId)}, callback);
};

Idea.getLeaderBoardStats = function (params, callback) {
    var fromDate = util.getDateWithoutTimeStamp(params.fromDate);
    var todate1 = util.getDateWithoutTimeStamp(params.toDate);
    var endDate = new Date(todate1.getTime() + (24 * 60 * 60 * 1000));

    // 省略时间 todo
    /*if (params.fromDate == undefined) {
        var searchMatch = {};
    } else {
        var searchMatch = {createdAt: {$gte: fromDate, $lt: endDate}};
    }*/

    var searchMatch = {};

    Idea.aggregate([
        {$match: searchMatch},
        {
            $group: {
                _id: "$user",
                totalIdeas: {$sum: 1},
                totalVotes: {$sum: "$points"},
            }
        },
        {"$sort": {"totalIdeas": -1}},
        {$limit: 10},
        {
            $lookup: {
                "from": "comments",
                "localField": "_id",
                "foreignField": "user",
                "as": "allComments"
            }
        },
        {
            "$project": {
                "_id": "$_id",
                "totalIdeas": "$totalIdeas",
                "totalVotes": "$totalVotes",
                "filteredComments": {
                    $filter: {
                        input: "$allComments", as: "num", cond: {
                            $and: [
                              /*  {$gte: ['$$num.createdAt', fromDate]},*/
                                {$lte: ['$$num.createdAt', endDate]},
                            ]
                        }
                    }
                }
            }
        },
        {
            "$project": {
                "_id": "$_id",
                "totalIdeas": "$totalIdeas",
                "totalComments": {$size: "$filteredComments"},
                "totalVotes": "$totalVotes"
            }
        },

        {"$sort": {"totalIdeas": -1, "totalComments": -1, "totalVotes": -1}},
        {
            $lookup: {
                "from": "users",
                "localField": "_id",
                "foreignField": "_id",
                "as": "users"
            }
        },
        {
            $unwind: "$users"
        },
        {
            "$project": {
                "_id": "$_id",
                "name": {$concat: ["$users.firstName", " ", {$ifNull: ["$users.lastName", " "]}]},
                "profileImageURL": "$users.profileImageURL",
                "aboutMe": "$users.aboutMe",
                "totalIdeas": "$totalIdeas",
                "totalComments": "$totalComments",
                "totalVotes": "$totalVotes"
            }
        },
    ], callback)
};

Idea.getAllIdeaCount = function (callback) {
    Idea.find().count(callback);
};

Idea.getUserIdeaCount = function (userId, callback) {
    Idea.find({user: Mongoose.Types.ObjectId(userId)}).count(callback);
};

Idea.getSpam = function (ideaId, callback) {
    Idea.findOne({_id: ideaId}).exec(function (err, idea) {
        if (!err) {
            var currentStatus = !idea.spam;
            idea.spam = currentStatus;
            idea.save(callback);
        }
    });
};

Idea.getCitationTreeData = function (input, callback) {
    var keywords = input.content;
    var searchMatch;
    var keyWordArray = [];
    var query = [];

    for (var i = 0; i < keywords.length; i++) {
        keyWordArray.push(keywords[i]);
        var temp = {};
        var temp1 = [];
        temp1.push("$$num.content", keywords[i]);
        temp.$eq = temp1;
        query.push(temp);
    }
    if (input.date) {

        var tempDate = util.getDateWithoutTimeStamp(input.date);
        var endDate = new Date(tempDate.getTime() + (24 * 60 * 60 * 1000));

        searchMatch = {
            $and: [
                {"createdAt": {$lte: endDate}},
                {
                    $and: [{
                        "keyword": {
                            $exists: true
                        }
                    }, {
                        "keyword.content": {
                            $in: keyWordArray
                        }
                    }]
                }]
        };
    } else {
        searchMatch = {
            $and: [{
                "keyword": {
                    $exists: true
                }
            }, {
                "keyword.content": {
                    $in: keyWordArray
                }
            }]
        };
    }
    Idea.aggregate([{
        "$match": searchMatch
    }, {
        $lookup: {
            "from": "users",
            "localField": "user",
            "foreignField": "_id",
            "as": "users"
        }
    }, {
        $unwind: "$users"
    }, {
        "$project": {
            "_id": "$_id",
            "users": "$users",
            "keyword": {
                $filter: {
                    input: "$keyword",
                    as: "num",
                    cond: {
                        $or: query
                    }
                }
            },
            "createdAt": "$createdAt"
        }
    }, {
        "$project": {
            "_id": "$_id",
            "createdAt": "$createdAt",
            "user": "$users._id",
            "keyword": "$keyword.content",
            "userImage": "$users.profileImageURL",
            "userName": {
                $concat: ["$users.firstName", " ", {
                    $ifNull: ["$users.lastName", " "]
                }]
            },
            "size": {
                $size: "$keyword"
            }
        }
    }, {
        "$sort": {
            "size": 1,
            "createdAt": 1,
            "keyword": 1
        }
    }], callback)
};

Idea.deleteIdea = function (ideaId, callback) {
    // Idea.findOneAndRemove({'_id': ideaId});
    Idea.find(
        {'_id': Mongoose.Types.ObjectId(ideaId)}
    ).remove(callback);
};



module.exports = Idea;